package com.xn.app.muying.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.activity.ChanJianDetailActivity;
import com.xn.app.muying.activity.DengLuActivity;
import com.xn.app.muying.activity.EducationDetailsActivity;
import com.xn.app.muying.activity.MainActivity;
import com.xn.app.muying.activity.MuYingApplication;
import com.xn.app.muying.R;
import com.xn.app.muying.activity.BabyStudyListActivity;
import com.xn.app.muying.activity.EducationActivity;
import com.xn.app.muying.activity.HosptialActivity;
import com.xn.app.muying.activity.JiuZhenActivity;
import com.xn.app.muying.activity.SeekActivity;
import com.xn.app.muying.activity.VoiceSolutionActivity;
import com.xn.app.muying.adpter.BabyStudyAdpter;
import com.xn.app.muying.bean.BabyStudyBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

/**
 * 知识
 * Created by Administrator on 2016/11/4.
 */
public class EducationFragment extends Fragment implements View.OnClickListener, HttpUtil.OnGetDataListener, AdapterView.OnItemClickListener {

    //标题栏
    private TextView title=null;
    //搜索按钮
    private TextView seek_textview = null;
    //健康宣教按钮布局
    private LinearLayout education_linearlayout = null;
    //动作
    private Intent intent = null;
    //医院资讯按钮
    private LinearLayout hosptial_linearlayout;
    //蓓儿课堂精选列表
    private MyGridView lv;
    //换一批
    private TextView batch=null;
    //布局滑动
    private ScrollView scrollview=null;
    private Handler handler = new Handler();
    private BabyStudyAdpter babyStudyAdpter;
    private ArrayList<BabyStudyBean> list;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //数据库
    private DBManager db = null;
    //获取用户姓名
    private String userName = null;
    //加载框
    AlertDialog dialog1;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 6;
    //接口访问参数
    //45 漫画科普
    //44 实用干货
    //43 小蓓食堂
    private final String data="45,44,43";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.education_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //得到数据库对象
        db = new DBManager(getContext());
        //加载并缓存图片
        imageLoader = MyImageLoader.getImageLoader(getActivity());
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();

        //初始化组件
        initialization(view);
        lv.setOnItemClickListener(this);
        babyStudyAdpter = new BabyStudyAdpter(getActivity(), imageLoader, options);
        lv.setAdapter(babyStudyAdpter);
        //加载缓存数据
        cache();
        //下载数据
        if (NetworkUtil.isNetworkAvailable(getActivity())) {
            HttpUtil.getData(APIMethod.BabyStudy(data,currentPage,number), handler, this);
        }else{
            if(dialog1!=null){
                dialog1.dismiss();
            }
            ToastUtil.showToast(getActivity(),R.string.no_network_hint);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (NetworkUtil.isNetworkAvailable(getActivity())) {
//            getUserInfo();
        }
    }

    /**
     * 初始化组件，并给相应控件添加单击事件
     * view
     */
    private void initialization(View view) {
        title= (TextView) view.findViewById(R.id.title);
        lv = (MyGridView) view.findViewById(R.id.education_fragment_gridview);
        education_linearlayout = (LinearLayout) view.findViewById(R.id.education_linearlayout);
        hosptial_linearlayout = (LinearLayout) view.findViewById(R.id.hosptial_linearlayout);
        seek_textview = (TextView) view.findViewById(R.id.seek_textview);
        scrollview = (ScrollView) view.findViewById(R.id.scrollview);
        batch= (TextView) view.findViewById(R.id.batch);
        education_linearlayout.setOnClickListener(this);
        hosptial_linearlayout.setOnClickListener(this);
        seek_textview.setOnClickListener(this);
        batch.setOnClickListener(this);
    }

    //加载框
    MyAlertDialog dialog;

    /**
     * 用户点击事件
     */
    @Override
    public void onClick(View view) {
        userName = db.select("tel");
        switch (view.getId()) {
            //健康宣教按钮点击事件
            case R.id.education_linearlayout:
                intent = new Intent(getActivity(), EducationActivity.class);
                startActivity(intent);
                break;
            //医院资讯点击事件
            case R.id.hosptial_linearlayout:
//                userName = db.select("tel");
//                final Intent intent1 = new Intent();
//                if (userName != null && !userName.equals("") && !userName.equals("null")) {
//                    String id = db.select("antenatalCareHospitalId");
//                    if (id != null && !id.equals("") && !id.equals("null")) {
//                        intent1.putExtra("antenatalCareHospitalId", id);
//                        intent1.setClass(getActivity(), HosptialActivity.class);
//                        startActivity(intent1);
//                    } else {
//                        try {
//                            //加载弹出框
//                            dialog = new MyAlertDialog();
//                            dialog.Prompt_Dialog(getContext(), R.layout.prompt_dialog);
//                            //设置内容
//                            TextView data = dialog.getData();
//                            data.setText("亲爱的麻麻，快去选择就诊医院吧！可查看医院精彩内容哟！");
//                            //设置取消按钮
//                            TextView getCancel_text = dialog.getCancel_text();
//                            getCancel_text.setText("返回");
//                            getCancel_text.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View view) {
//                                    dialog.dismiss();
//                                }
//                            });
//                            //设置确认按钮
//                            TextView getConfirm_text = dialog.getConfirm_text();
//                            getConfirm_text.setText("设置");
//                            getConfirm_text.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View view) {
//                                    dialog.dismiss();
//                                    intent = new Intent();
//                                    intent.putExtra("SIGN", "return");
//                                    intent.setClass(getActivity(), JiuZhenActivity.class);
//                                    startActivity(intent);
//                                }
//                            });
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                } else {
//                    //如果没有登陆，调整到登陆页面
//                    startActivity(new Intent(getActivity(), DengLuActivity.class));
//                }
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    intent = new Intent(getActivity(), VoiceSolutionActivity.class);
                    startActivity(intent);
                }else {
                    //如果没有登陆，调整到登陆页面
                    startActivity(new Intent(getActivity(), DengLuActivity.class));
                }
                break;
            //搜索框点击事件
            case R.id.seek_textview:
                Intent intent = new Intent(getActivity(), SeekActivity.class);
                startActivity(intent);
                break;
            //换一批
            case R.id.batch:
                if (NetworkUtil.isNetworkAvailable(getActivity())) {
                    dialog1 = new MyAlertDialog().ShowDialog(getActivity(), R.layout.dialog_loading);
                    dialog1.setCancelable(true);
                    if(lv.getVisibility()==View.VISIBLE){
                        lv.setVisibility(View.GONE);
                    }
                    if (totalCount > currentPage * number) {
                        currentPage = currentPage + 1;
                    } else {
                        currentPage=1;
                    }
                    HttpUtil.getData(APIMethod.BabyStudy(data,currentPage,number), handler, this);
                }else{
                    ToastUtil.showToast(getActivity(),R.string.no_network_hint);
                }

                break;
        }
    }

    //获取用户信息，判断是否设置医院
    private void getUserInfo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.UserInfo).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    onJsonInfo(bodys);
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    private void onJsonInfo(String bodys) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onJsonData(String data) {
        try {
            JSONObject object =new JSONObject(data);
            //获取数据总量
            if (totalCount == 0) {
                totalCount = Integer.parseInt(object.get("totalCount").toString());
            }
            JSONArray array = object.getJSONArray("items");
            list = new ArrayList<>();
            for (int i = 0; i < array.length(); i++) {
                object = array.getJSONObject(i);
                String title = object.optString("title");
                String pictureUrl = object.optString("pictureUrl");
                String id = object.optString("id");
                String shortDescription= object.optString("shortDescription");
                String creationTime=object.optString("creationTime");
                if(creationTime.length()>10){
                    creationTime=creationTime.substring(5,10).replace("-","月")+"日";
                }
                object = new JSONObject(object.getString("category"));
                String name = object.optString("name");
                BabyStudyBean babyStudyBean = new BabyStudyBean();
                babyStudyBean.setName(name);
                babyStudyBean.setTitle(title);
                babyStudyBean.setShortDescription(shortDescription);
                babyStudyBean.setCreationTime(creationTime);
                babyStudyBean.setPictureUrl(pictureUrl);
                babyStudyBean.setId(id);
                list.add(babyStudyBean);
            }
            babyStudyAdpter.getData(list);
            if(dialog1!=null){
                dialog1.dismiss();
            }
            if(lv.getVisibility()!=View.VISIBLE){
                lv.setVisibility(View.VISIBLE);
            }
            //添加缓存数据
            if (db.selectNull(DBManager.CACHE_TABLE) != 0) {
                db.updateCache(data, "classroom");
            } else {
                db.insertCache(data, "classroom");
            }
            title.setFocusable(true);
            title.setFocusableInTouchMode(true);
            title.requestFocus();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (i <list.size()) {
            Intent intent = new Intent();
            intent.putExtra("type", 1);
            intent.putExtra("id", list.get(i).getId());
            intent.putExtra("name", list.get(i).getName());
            intent.putExtra("title", list.get(i).getTitle());
            intent.putExtra("content", list.get(i).getShortDescription());
            intent.putExtra("pic",list.get(i).getPictureUrl());
            intent.setClass(getActivity(), EducationDetailsActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 缓存的数据
     */
    private void cache() {
        dialog1 = new MyAlertDialog().ShowDialog(getActivity(), R.layout.dialog_loading);
        dialog1.setCancelable(false);
        //保存蓓儿课堂数据
        String data = db.selectCache("classroom");
        if (data != null && !data.equals("") && !data.equals("null")) {
            try {
                JSONObject object1 =new JSONObject(data);
                JSONArray array =object1.getJSONArray("items");
                list = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = array.getJSONObject(i);
                    String title = object.optString("title");
                    String pictureUrl = object.optString("pictureUrl");
                    String id = object.optString("id");
                    String shortDescription= object.optString("shortDescription");
                    String creationTime=object.optString("creationTime");
                    creationTime=creationTime.substring(5,10).replace("-","月")+"日";
                    object = new JSONObject(object.getString("category"));
                    String name = object.optString("name");
                    BabyStudyBean babyStudyBean = new BabyStudyBean();
                    babyStudyBean.setName(name);
                    babyStudyBean.setTitle(title);
                    babyStudyBean.setShortDescription(shortDescription);
                    babyStudyBean.setCreationTime(creationTime);
                    babyStudyBean.setPictureUrl(pictureUrl);
                    babyStudyBean.setId(id);
                    list.add(babyStudyBean);
                }
                babyStudyAdpter.getData(list);
                if(dialog1!=null){
                    dialog1.dismiss();
                }
                if(lv.getVisibility()!=View.VISIBLE){
                    lv.setVisibility(View.VISIBLE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
